<?php
/**
 * 《IP地址》实现类
 * 
 * @author 孙晓晔
 * @version $Id: IpAddr.class.php,v 1.1 2009/02/16 07:36:07 sunxy Exp $
 */

class IpAddr {

	function __construct() {
		$request['update'] = '$Date: 2009/02/16 07:36:07 $';
		$request['revision'] = '$Revision: 1.1 $';
	}

	/**
	 * 预处理
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function pretreat(& $controller, & $request) {
	}

	/**
	 * Matches:
	 * xxx.xxx.xxx.xxx        (exact)
	 * xxx.xxx.xxx.[yyy-zzz]  (range)
	 * xxx.xxx.xxx.xxx/nn     (CIDR)
	 * xxx.xxx.xxx.xxx/xxx.xxx.xxx.xxx
	 * 
	 * Does not match:
	 * xxx.xxx.xxx.xx[yyy-zzz]  (range, partial octets not supported)
	 * 
	 * @param   string   string of IP range to match
	 * @param   string   string of IP to test against range
	 * 
	 * @return  boolean    always true
	 * @access  public
	 */
	function contains($range, $ipaddr) {

		if ($range == $ipaddr) {
			return true;
		}
		
		if (preg_match('|([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)/([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)|', $range, $regs)) {
			$ipl = ip2long($ipaddr);
			$rangel = ip2long($regs[1] . '.' . $regs[2] . '.' . $regs[3] . '.' . $regs[4]);
			$maskl = ip2long($regs[5] . '.' . $regs[6] . '.' . $regs[7] . '.' . $regs[8]);
			
			if (($maskl & $rangel) == ($maskl & $ipl)) {
				return true;
			} else {
				return false;
			}		
		}

		if (preg_match('|([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)/([0-9]+)|', $range, $regs)) {
			$ipl = ip2long($ipaddr);
			$rangel = ip2long($regs[1] . '.' . $regs[2] . '.' . $regs[3] . '.' . $regs[4]);
			
			$maskl = 0;

			for ($i = 0; $i < 31; $i++) {
				if ($i < $regs[5]) {
					$maskl = $maskl + pow(2, (31 - $i));
				}
			}

			if (($maskl & $rangel) == ($maskl & $ipl)) {
				return true;
			} else {
				return false;
			}
		}

		$result = true;
		$mask = explode('.', $range);
		$ip = explode('.', $ipaddr);

		for ($i = 0; $i < 4; $i++) {
			if (preg_match('|\[([0-9]+)\-([0-9]+)\]|', $mask[$i], $regs)) {
				if ($ip[$i] > $regs[2] || $ip[$i] < $regs[1]) {
					$result = false;
				}
			} else {
				if ($mask[$i] != $ip[$i]) {
					return false;
				}
			}
		}

		return $result;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function t($controller, $request) {		
		if ($this->contains("211.99.191.8/29", "211.99.191.9")) {
			echo "OK...";
		} else {
			echo "222";
		}
		
		if ($this->contains("211.99.191.0/255.255.255.246", "211.99.191.9")) {
			echo "OK...";
		} else {
			echo "222";
		}

		if ($this->contains("211.99.[190-194].0", "211.99.194.9")) {
			echo "OK...";
		} else {
			echo "222";
		}

		logdate($controller, $request);
		return true;
	}
}
?>
